package tech.luoyu.ki.intercepter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import tech.luoyu.ki.entity.auto.SysUser;
import tech.luoyu.ki.service.UserService;
import tech.luoyu.ki.util.SessionUtil;

@Component
public class SessionInterceptor implements HandlerInterceptor {
	private final Log LOG = LogFactory.getLog(SessionInterceptor.class);

	@Resource
	private UserService userInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		if (request.getSession(true).getAttribute("user") == null) {
			Subject currentUser = SecurityUtils.getSubject();
			// 用户如果已经登陆，初始化session
			if (currentUser.isAuthenticated() || currentUser.isRemembered()) {
				if (currentUser.isAuthenticated()) {
					LOG.info("授权登陆！");
				} else {
					LOG.info("RememberMe登陆！");
				}
				SysUser user = (SysUser) currentUser.getPrincipal();
				SessionUtil.setAttribute("user", user);
			}
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object o, Exception e) throws Exception {
	}
}
